import React, { useState } from 'react';
import { Layout, Card, Radio, Button, Row, Col, Space, message, Spin } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import metahumanService from '@/api/services/metahumanService';
import { MetahumanResource } from '@/types/metahuman';
import MetahumanModal from './metahuman-modal';
import ApplicationCard from './application-card';
import './metahuman.css';

const { Content } = Layout;

interface ApplicationCard {
  id: string;
  name: string;
  description: string;
  connectionLimit?: number;
  isAuthorized?: boolean;
  appAvatar?: string;
}

interface MetahumanPermissionProps {
  authorizedApplications?: ApplicationCard[];
}

const MetahumanPermission: React.FC<MetahumanPermissionProps> = ({ 
  authorizedApplications: propAuthorizedApplications
}) => {
  const { isPc } = useWindowWidth();
  const [permissionType, setPermissionType] = useState<'restrict' | 'no-restrict'>('restrict');
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [currentApps, setCurrentApps] = useState<MetahumanResource[]>([]);
  const [localAuthorizedApps, setLocalAuthorizedApps] = useState<ApplicationCard[]>([]);

  // 使用 useRequest 获取权限状态数据
  const { data: permissionData, loading, error, run } = useRequest(
    async () => {
      const response = await metahumanService.getMetahumanPermissionStatus();
      return response.resources;
    },
    {
      manual: !!propAuthorizedApplications, // 如果传入了props数据，则手动触发
      onError: (error) => {
        console.error('获取数字人权限状态失败:', error);
        message.error('获取权限状态失败');
      }
    }
  );

  // 创建数字人权限
  const { runAsync: createPermission, loading: createLoading } = useRequest(
    async (appIds: string[], maxConnections: number) => {
      const response = await metahumanService.createMetahumanPermission({
        appIds,
        maxConnections
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        message.success('权限创建成功');
        run(); // 刷新权限状态数据
      },
      onError: (error) => {
        console.error('创建数字人权限失败:', error);
        // message.error('权限创建失败');
      }
    }
  );

  // 更新数字人权限
  const { runAsync: updatePermission, loading: updateLoading } = useRequest(
    async (appId: string, maxConnections: number) => {
      const response = await metahumanService.updateMetahumanPermission({
        appId,
        maxConnections
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        message.success('权限更新成功');
        run(); // 刷新权限状态数据
      },
      onError: (error) => {
        console.error('更新数字人权限失败:', error);
        // message.error('权限更新失败');
      }
    }
  );

  // 删除数字人权限
  const { runAsync: deletePermission, loading: deleteLoading } = useRequest(
    async (appId: string) => {
      const response = await metahumanService.deleteMetahumanPermission({
        appId
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        message.success('权限删除成功');
        run(); // 刷新权限状态数据
      },
      onError: (error) => {
        console.error('删除数字人权限失败:', error);
        // message.error('权限删除失败');
      }
    }
  );

  // 更新全局数字人权限配置
  const { runAsync: updateGlobalPermission, loading: globalPermissionLoading } = useRequest(
    async (metahumanEnabled: boolean) => {
      const response = await metahumanService.updateMetahumanGlobalPermission({
        metahumanEnabled
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        // message.success('全局权限配置更新成功');
      },
      onError: (error) => {
        console.error('更新全局数字人权限配置失败:', error);
        // message.error('全局权限配置更新失败');
      }
    }
  );

  // 获取全局数字人权限状态
  const { loading: globalStatusLoading } = useRequest(
    async () => {
      const response = await metahumanService.getMetahumanGlobalPermissionStatus();
      return response;
    },
    {
      onSuccess: (data) => {
        // 根据全局权限状态设置默认的权限类型
        const defaultPermissionType = data.metahumanGlobalEnabled ? 'no-restrict' : 'restrict';
        setPermissionType(defaultPermissionType);
      },
      onError: (error) => {
        console.error('获取全局数字人权限状态失败:', error);
      }
    }
  );

  // 处理数据转换
  const getAuthorizedApplications = (): ApplicationCard[] => {
    // 如果传入了props数据，优先使用props数据
    if (propAuthorizedApplications) {
      return propAuthorizedApplications;
    }

    // 如果API请求失败或没有数据，使用默认数据
    if (error || !permissionData) {
      return [
        { id: '1', name: '应用名称', description: '应用详情描述', connectionLimit: 5, isAuthorized: true },
        { id: '2', name: '应用名称', description: '应用详情描述', connectionLimit: 5, isAuthorized: true },
        { id: '3', name: '应用名称', description: '应用详情描述', connectionLimit: 5, isAuthorized: true },
      ];
    }

    // 将API数据转换为组件需要的格式
    return permissionData.map((resource: MetahumanResource) => ({
      id: resource.appId,
      name: resource.appName,
      description: resource.appDescription,
      connectionLimit: resource.maxConnections,
      isAuthorized: true, // 从权限状态接口获取的数据都是已授权的
      appAvatar: resource.appAvatar
    }));
  };

  // 获取最终显示的应用列表（优先使用本地状态，然后是API数据）
  const getDisplayApplications = (): ApplicationCard[] => {
    if (localAuthorizedApps.length > 0) {
      return localAuthorizedApps;
    }
    return getAuthorizedApplications();
  };

  const authorizedApplications = getDisplayApplications();

  // 事件处理函数
  const handleAddApplication = () => {
    // 将当前应用数据转换为 MetahumanResource 格式
    const currentAppResources: MetahumanResource[] = authorizedApplications.map(app => ({
      appId: app.id,
      appName: app.name,
      appDescription: app.description,
      appAvatar: app.appAvatar || '',
      maxConnections: app.connectionLimit || 5,
      activeConnections: 0
    }));
    setCurrentApps(currentAppResources);
    setIsAddModalVisible(true);
  };

  const handleModalOk = async (selectedApps: MetahumanResource[]) => {
    try {
      // 提取应用ID和连接数
      const appIds = selectedApps.map(app => app.appId);
      const maxConnections = selectedApps[0]?.maxConnections || 5; // 使用第一个应用的连接数作为默认值
      
      // 调用创建权限API
      await createPermission(appIds, maxConnections);
      
      // 将新选择的应用转换为 ApplicationCard 格式
      const newAppCards: ApplicationCard[] = selectedApps.map(app => ({
        id: app.appId,
        name: app.appName,
        description: app.appDescription,
        connectionLimit: app.maxConnections,
        isAuthorized: true,
        appAvatar: app.appAvatar
      }));

      // 合并现有应用和新应用，去重
      const allApps = [...authorizedApplications, ...newAppCards];
      const uniqueApps = allApps.filter(
        (app, index, self) => index === self.findIndex((a) => a.id === app.id)
      );

      // 更新本地状态
      setLocalAuthorizedApps(uniqueApps);
      
      setIsAddModalVisible(false);
    } catch (error) {
      console.error('添加应用失败:', error);
    }
  };

  const handleModalCancel = () => {
    setIsAddModalVisible(false);
  };

  const handleDeleteApplication = async (appId: string) => {
    try {
      // 调用删除权限API
      await deletePermission(appId);
      
      // 从本地状态中删除应用
      const updatedApps = authorizedApplications.filter(app => app.id !== appId);
      setLocalAuthorizedApps(updatedApps);
    } catch (error) {
      console.error('删除应用失败:', error);
    }
  };

  const handleConfigApplication = async (appId: string, connectionLimit: number) => {
    try {
      // 调用更新权限API
      await updatePermission(appId, connectionLimit);
      
      // 更新本地状态
      const updatedApps = authorizedApplications.map(app => 
        app.id === appId ? { ...app, connectionLimit } : app
      );
      setLocalAuthorizedApps(updatedApps);
    } catch (error) {
      console.error('更新应用配置失败:', error);
    }
  };

  const handlePermissionChange = async (value: 'restrict' | 'no-restrict') => {
    try {
      // 根据选择的值设置 metahumanEnabled
      // restrict = 限制使用 = false, no-restrict = 不限制 = true
      const metahumanEnabled = value === 'no-restrict';
      
      // 调用全局权限配置更新接口
      await updateGlobalPermission(metahumanEnabled);
      
      // 更新本地状态
      setPermissionType(value);
    } catch (error) {
      console.error('更新权限设置失败:', error);
      // 如果接口调用失败，不更新本地状态
    }
  };

  // 合并所有loading状态
  const isLoading = loading || createLoading || updateLoading || deleteLoading;

  if (isLoading) {
    return (
      <Layout style={{ background: 'transparent' }}>
        <Content style={{ padding: '0px', textAlign: 'center', paddingTop: '50px' }}>
          <Spin size="large" />
        </Content>
      </Layout>
    );
  }

  return (
    <Layout style={{ background: 'transparent' }}>
      <Content style={{ padding: '0px' }}>        
        {/* 权限选项 */}
        <Card
          className="permission-card"
          bodyStyle={{ padding: '20px' }}
        >
          <Radio.Group
            value={permissionType}
            onChange={(e) => handlePermissionChange(e.target.value)}
            style={{ width: '100%' }}
          >
            <Space direction="horizontal" size="large" style={{ width: '100%' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <Radio value="restrict" />
                <div>
                  <div style={{ fontSize: '16px', fontWeight: '500', color: '#1D1E51', marginBottom: '4px' }}>
                    限制使用
                  </div>
                  <div style={{ fontSize: '14px', color: '#8A8EA7' }}>
                    仅授权应用可开启数字人
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <Radio value="no-restrict" />
                <div>
                  <div style={{ fontSize: '16px', fontWeight: '500', color: '#1D1E51', marginBottom: '4px' }}>
                    不限制
                  </div>
                  <div style={{ fontSize: '14px', color: '#8A8EA7' }}>
                    所有智能体均能开启数字人
                  </div>
                </div>
              </div>
            </Space>
          </Radio.Group>
        </Card>

        {/* 添加应用按钮 */}
        <div className="flex my-5">
          <Button
            type="primary"
            size="large"
            icon={<PlusOutlined />}
            onClick={handleAddApplication}
            className="add-button"
          >
            添加应用
          </Button>
        </div>

        {/* 授权应用列表 */}
        <Row gutter={[16, 16]}>
          {authorizedApplications.map((app, index) => (
            <Col key={app.id} xs={24} sm={12} md={8} lg={8} xl={8}>
              <ApplicationCard
                id={app.id}
                name={app.name}
                description={app.description}
                connectionLimit={app.connectionLimit}
                icon={app.appAvatar}
                isPreview={false}
                onConfig={handleConfigApplication}
                onDelete={handleDeleteApplication}
              />
            </Col>
          ))}
        </Row>

        {/* 数字人应用选择模态框 */}
        <MetahumanModal
          open={isAddModalVisible}
          onOk={handleModalOk}
          onCancel={handleModalCancel}
          existingApps={currentApps}
        />
      </Content>
    </Layout>
  );
};

export default MetahumanPermission; 